﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Ecobee.Net
{
	public class ResponseCodeExceptionFactory : IResponseCodeExceptionFactory
	{
		private readonly List<ResponseCodeException> _responseCodeExceptions = new List<ResponseCodeException>();

		public ResponseCodeExceptionFactory()
		{
			this.ResponseCodeExceptions.Add(new AuthenticationFailed(null));
			this.ResponseCodeExceptions.Add(new NotAuthorized(null));
			this.ResponseCodeExceptions.Add(new ProcessingError(null));
			this.ResponseCodeExceptions.Add(new SerializationError(null));
			this.ResponseCodeExceptions.Add(new InvalidRequestFormat(null));
			this.ResponseCodeExceptions.Add(new TooManyThermostats(null));
			this.ResponseCodeExceptions.Add(new ValidationError(null));
			this.ResponseCodeExceptions.Add(new InvalidFunction(null));
			this.ResponseCodeExceptions.Add(new InvalidSelection(null));
			this.ResponseCodeExceptions.Add(new InvalidPage(null));
			this.ResponseCodeExceptions.Add(new FunctionError(null));
			this.ResponseCodeExceptions.Add(new PostNotSupported(null));
			this.ResponseCodeExceptions.Add(new GetNotSupported(null));
			this.ResponseCodeExceptions.Add(new AuthenticationTokenExpired(null));
			this.ResponseCodeExceptions.Add(new DuplicateDataViolation(null));
			this.ResponseCodeExceptions.Add(new InvalidToken(null));
		}

		public List<ResponseCodeException> ResponseCodeExceptions
		{
			get
			{
				return _responseCodeExceptions;
			}
		}

		public ResponseCodeException CreateInstance(int responseCode, Exception innerException)
		{
			ResponseCodeException returnValue = null;

			var qry = from tbl in this.ResponseCodeExceptions
					  where tbl.ResponseCode == responseCode
					  select tbl;

			if (qry.Count() == 1)
			{
				returnValue = (ResponseCodeException)Activator.CreateInstance(qry.Single().GetType(), new object[] {innerException});
			}

			return returnValue;
		}
	}
}
